﻿using System.Web.Mvc;
using MugenInjection.Infrastructure;
using MugenInjection.Interface;
using MugenInjection.Web.Interface;
using System.Linq;

namespace MugenInjection.Web.Mvc.Config
{
    /// <summary>
    /// Providing integration with MVC.
    /// </summary>
    public class MugenInjectionMvcApplicationConfig : IConfiguration
    {
        #region Implementation of IConfiguration

        /// <summary>
        /// Loads the current configuration.
        /// </summary>
        /// <param name="configuration">The specified <see cref="IApplicationConfiguration"/>.</param>
        public void Load(IApplicationConfiguration configuration)
        {
            Validate.ArgumentNotNull(configuration, "configuration");
            Validate.ArgumentNotNull(configuration.Injector, "configuration.Injector");
            IInjector injector = configuration.Injector;
            if (!injector.CanResolve(typeof(IControllerFactory), true, false))
                injector.BindWithManualBuild<IControllerFactory>()
                        .ToConstant(new MugenInjectionControllerFactory(injector))
                        .Build();

            var oldValidator = ModelValidatorProviders
                .Providers
                .FirstOrDefault(provider => provider is DataAnnotationsModelValidatorProvider);
            if (oldValidator != null)
                ModelValidatorProviders.Providers.Remove(oldValidator);
#if MVC2
            ModelValidatorProviders.Providers.Add(new MugenInjectionDataAnnotationsModelValidatorProvider(injector));
            ControllerBuilder.Current.SetControllerFactory(injector.Get<IControllerFactory>());            
#else
            injector.BindWithManualBuild<ModelValidatorProvider>()
                    .ToConstant(new MugenInjectionDataAnnotationsModelValidatorProvider(injector))
                    .Build();

            var oldProvider = FilterProviders.Providers.FirstOrDefault(f => f is FilterAttributeFilterProvider);
            if (oldProvider != null)
                FilterProviders.Providers.Remove(oldProvider);

            injector.BindWithManualBuild<IFilterProvider>()
                    .ToConstant(new MugenInjectionFilterAttributeFilterProvider(injector))
                    .Build();
            IDependencyResolver dependencyResolver;
            injector.TryGet(out dependencyResolver);
            if (dependencyResolver == null)
                dependencyResolver = new MugenInjectionDependencyResolver(injector);
            DependencyResolver.SetResolver(dependencyResolver);
#endif
        }

        /// <summary>
        /// Unloads the current configuration.
        /// </summary>
        /// <param name="configuration">The specified <see cref="IApplicationConfiguration"/>.</param>
        public void Unload(IApplicationConfiguration configuration)
        {
        }

        #endregion
    }
}